package com.frank.fresh_mall.filter;

import com.frank.fresh_mall.common.Constant;
import com.frank.fresh_mall.model.pojo.User;
import com.frank.fresh_mall.service.UserService;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 管理员校验过滤器
 */
public class AdminFilter implements Filter {
    @Resource
    private UserService userService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    // 登录和管理员权限的校验
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpSession session = req.getSession();
        User currentUser = (User) session.getAttribute(Constant.FRESH_MALL_USER);
        if (currentUser == null) { // 没有登录
            PrintWriter out = new HttpServletResponseWrapper(
                    (HttpServletResponse) response).getWriter();
            out.write("{\n"
                    + "    \"status\": 10007,\n"
                    + "    \"msg\": \"NEED_LOGIN\",\n"
                    + "    \"data\": null\n"
                    + "}");
            out.flush();
            out.close();
            return;
        }
        if (!userService.checkAdminRole(currentUser)) { // 不是管理员
            PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) response).getWriter();

            out.write("{\n" +
                    "\"status\": 10009,\n" +
                    "\"msg\": \"NEED_ADMIN\",\n" +
                    "\"data\": null\n" +
                    "}");
            out.flush();
            out.close();
            return;
        }
        // 放行
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
